package com.xuecheng.media.service.impl;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.api.media.MediaDTO;
import com.xuecheng.api.media.model.vo.MediaVO;
import com.xuecheng.common.domain.code.CommonErrorCode;
import com.xuecheng.common.domain.page.PageRequestParams;
import com.xuecheng.common.enums.common.AuditEnum;
import com.xuecheng.common.exception.ExceptionCast;
import com.xuecheng.common.util.StringUtil;
import com.xuecheng.media.common.constant.MediaErrorCode;
import com.xuecheng.media.common.utils.AliyunVODUtil;
import com.xuecheng.media.convert.MediaConvert;
import com.xuecheng.media.entity.Media;
import com.xuecheng.api.media.model.vo.PreviewMedia;
import com.xuecheng.media.mapper.MediaMapper;
import com.xuecheng.media.service.MediaService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Collections;
import java.util.List;

/**
 * @author by it-song
 * @Date 2021/12/15
 * @Description
 */
@Service
public class MediaServiceImpl extends ServiceImpl<MediaMapper, Media> implements MediaService {

    /*
     * 业务分析：
     *   1.判断关键
     *       companyid  filename  fileid(videoId)
     *   2.给信息数据赋值默认值
     *       auditStatus：未审核
     *
     *   3.保存信息
     *   4.将数据库最新数据返回
     *
     * */

    @Override
    public MediaDTO createMedia(MediaDTO dto) {
//todo 创建媒资管理联系
        // 1.判断关键
        //companyid  filename  fileid(videoId)
        if (ObjectUtils.isEmpty(dto.getCompanyName()) ||
                StringUtil.isBlank(dto.getFileId()) ||
                StringUtil.isBlank(dto.getFileId())
        ) {
            ExceptionCast.cast(CommonErrorCode.E_100101);
        }
        //*   2.给信息数据赋值默认值
        //     auditStatus：未审核
        dto.setAuditStatus(AuditEnum.AUDIT_UNPAST_STATUS.getCode());

        Media media = MediaConvert.INSTANCE.dto2entity(dto);
        boolean save = this.save(media);
        if (!save) {
            ExceptionCast.cast(MediaErrorCode.E_140001);
        }
        //从数据库中获取新的数据
        Media id = this.getById(media.getId());
        //转换属性
        MediaDTO mediaDTO = MediaConvert.INSTANCE.entity2dto(id);
        return mediaDTO;
    }


    @Override
    public PreviewMedia previewMediaList(PageRequestParams params, MediaVO mediaVO, Long companyId) {
        //判断关键数据 当前页 每页条数
        if (params.getPageNo() < 1) {
            params.setPageNo(PageRequestParams.DEFAULT_PAGE_NUM);
        }
        if (params.getPageSize() < 1) {
            params.setPageSize(PageRequestParams.DEFAULT_PAGE_SIZE);
        }
        if (ObjectUtils.isEmpty(companyId)) {
            ExceptionCast.cast(CommonErrorCode.E_110001);
        }

        Page<Media> mediaPage = new Page<>(params.getPageNo(), params.getPageSize());

        LambdaQueryWrapper<Media> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Media::getCompanyId, companyId);
        //选择性判断 有则判断 无则放行
        if (!ObjectUtils.isEmpty(mediaVO.getFilename())) {
            queryWrapper.eq(Media::getFilename, mediaVO.getFilename());
        }
        if (!ObjectUtils.isEmpty(mediaVO.getFileId())) {
            queryWrapper.eq(Media::getFileId, mediaVO.getFileId());
        }

        List<Media> list = this.list(queryWrapper);

        Page<Media> page = this.page(mediaPage, queryWrapper);

        PreviewMedia media = new PreviewMedia();
        media.setItems(Collections.singletonList(list));
        media.setPage((int) page.getCurrent());
        media.setPageSize((int) page.getSize());
        media.setPages((int) page.getPages());
        return media;
    }

    /*
     * 1 判断关键数据
     *      mediaID  companyId
     * 2 判断业务数据
     *      媒资信息是否存在 mediaId companyId
     *       判断业务类型 视频的话 直接获取阿里云的视频点播播放地址
     * 3 获得媒资资源路径的url
     *   获得最新的播放地址 从阿里云上获得视频点播地址
     *
     *
     * */
    @Override
    public String getVODUrl(Long mediaId, Long companyId) {
        //判断关键数据
        if (ObjectUtils.isEmpty(mediaId)) {
            ExceptionCast.cast(CommonErrorCode.E_100101);
        }
        Media byId = this.getById(mediaId);
        if (ObjectUtils.isEmpty(byId)) {
            ExceptionCast.cast(CommonErrorCode.E_100104);
        }
        if (ObjectUtils.isEmpty(companyId)) {
            if (ObjectUtils.nullSafeEquals(byId.getCompanyId(), companyId)) {
                ExceptionCast.cast(CommonErrorCode.E_100108);
            }
        }
        //查询阿里云
        String PlayUrl = getPlayUrl(byId.getFileId());
        //返回结果
        return PlayUrl;
    }


    @Value("${aliyun.region}")
    private String region;
    @Value("${aliyun.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.accessKeySecret}")
    private String accessKeySecret;

    private String getPlayUrl(String fileId) {

        String playUrl = "";

        try {

            DefaultAcsClient client =
                    AliyunVODUtil.initVodClient(region, accessKeyId, accessKeySecret);

            GetPlayInfoResponse response = AliyunVODUtil.getPlayInfo(client, fileId);

            List<GetPlayInfoResponse.PlayInfo> playInfoList = response.getPlayInfoList();

            if (!(ObjectUtils.isEmpty(playInfoList))) {
                GetPlayInfoResponse.PlayInfo playInfo = playInfoList.get(0);
                playUrl = playInfo.getPlayURL();
            }

        } catch (Exception e) {
            ExceptionCast.cast(MediaErrorCode.E_140014);
        }

        return playUrl;
    }


    /* 1 判断关键数据
     * 2 判断业务数据  是否有
     * 3 发送远端请求 删除阿里云上的视频
     * 4 响应数据
     * 5 返回前端是否成功
     * */
    @Override
    public Boolean deleteById(String mediaId, Long companyId) {
        if (ObjectUtils.isEmpty(mediaId)) {
            ExceptionCast.cast(CommonErrorCode.E_100116);
        }
        Media id = this.getById(mediaId);
        if (ObjectUtils.nullSafeEquals(id.getCompanyId(), companyId)) {
            ExceptionCast.cast(CommonErrorCode.E_100116);
        }
     //TODO宋恒利
        return null;
    }
}
